package com.hz.zbl.controller;

import com.hz.zbl.entity.BlogEntity;
import com.hz.zbl.entity.CommentsEntity;
import com.hz.zbl.mapper.BlogMapper;
import com.hz.zbl.model.request.ApiResponse;
import com.hz.zbl.service.BlogService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {

    @Resource
    BlogService blogService;

    @PostMapping("/add-blog")
    public String addBlog(@RequestParam("title") String title,
                          @RequestParam("content") String content,
                          @RequestParam("author_id") int user_id,
                          @RequestParam("anonymous") Integer is_anonymous
                          ){
        int result = blogService.addBlog(title, content, user_id, is_anonymous == 1);
        return result > 0 ? ApiResponse.ok(result) : ApiResponse.intError();
    }


    @PostMapping("/view-blog")
    public String viewBlog(@RequestParam("id") int id){
        return blogService.viewBlog(id) != null ? ApiResponse.ok(blogService.viewBlog(id)) : ApiResponse.intError();
    }


    @PostMapping("/delete-blog")
    public String deleteBlog(@RequestParam("id") int id){
        return blogService.deleteBlog(id) > 0 ? ApiResponse.ok(blogService.deleteBlog(id)) : ApiResponse.intError();
    }

    @PostMapping("/edit-blog")
    public String editBlog(@RequestParam("id") int id,
                           @RequestParam("title") String title,
                           @RequestParam("content") String content){


        return blogService.updateBlog(id, title, content) > 0 ? ApiResponse.ok(blogService.updateBlog(id, title, content)) : ApiResponse.intError();
    }


    @GetMapping("/all-blogs")
    public String allBlogs(){

        return ApiResponse.ok(blogService.allBlogs());
    }

    @PostMapping("/my-blogs")
    public List<BlogEntity> myBlogs(@RequestParam("author_id") int author_id){

        return blogService.myBlogs(author_id);
    }



    //博客评论
    @PostMapping("/add-comments-blogs")
    public String addCommentsBlogs(@RequestParam("blog_id") Integer blog_id,
                                @RequestParam("username") String username,
                                @RequestParam("content") String content,
                                @RequestParam(value = "is_anonymous", defaultValue = "0") Integer is_anonymous){

        int res = blogService.addComments(blog_id, username, content, is_anonymous == 1);
        return res == 1 ? ApiResponse.ok(res) : ApiResponse.intError();
    }

}
